package fg

import (
	"github.com/kataras/iris/websocket"
	"github.com/kataras/iris/context"
	"fmt"
)

const (
	WEBSOCKET_NAME = "/gchat"
)

type fg struct {
	Ws *websocket.Server
	Name string
	Handler context.Handler

}

func NewFg() *fg{
	f := new(fg)
	f.Ws = websocket.New(websocket.Config{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		EvtMessagePrefix: []byte("yu:"),
	})
	f.Name = WEBSOCKET_NAME
	f.Handler = f.Ws.Handler()
	//连接处理
	f.Ws.OnConnection(onConnectionHandler)

	return f
}


// 连接处理
func onConnectionHandler(c websocket.Connection) {
	c.On("chat", func(msg string) {
		fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)
		fmt.Println(c.ID())
		c.To(websocket.Broadcast).Emit("chat", msg)
	})
}